package cn.yunyichina.provider.message.thread.app;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.AlipayService;
import cn.yunyichina.provider.framework.dubbo.service.WechatPayService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.iface.entity.wechat.WechatMessageNewsImgVo;
import cn.yunyichina.provider.message.dao.ImageTemplateDao;
import cn.yunyichina.provider.message.dao.ImageTemplateListDao;
import cn.yunyichina.provider.message.entity.ImageTemplate;
import cn.yunyichina.provider.message.entity.ImageTemplateList;
import cn.yunyichina.provider.message.entity.OrgAppTemplate;
import cn.yunyichina.provider.message.utils.MsgAppUtils;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 图文消息推送线程
 * Created by Joe.zhou on 2017/12/13.
 */
public class MsgImgAppPushRunnable implements Runnable{
    private static Logger logger = LoggerFactory.getLogger(MsgImgAppPushRunnable.class);

    private final String METHOD_NAME = "MsgImgAppPushRunnable";

    private AppMessageVo appMessageVo;

    private ResponseObject responseObject;

    private ImageTemplateDao imageTemplateDao = SpringContextHandler.getBean(ImageTemplateDao.class);

    private ImageTemplateListDao imageTemplateListDao = SpringContextHandler.getBean(ImageTemplateListDao.class);

    public MsgImgAppPushRunnable(AppMessageVo appMessageVo, ResponseObject responseObject) {
        this.appMessageVo = appMessageVo;
        this.responseObject = responseObject;
    }

    @Override
    public void run() {
        Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.REQUEST,appMessageVo.getOpenId(), JsonUtils.toJsonString(appMessageVo));
        try {
            if(appMessageVo != null){
                OrgAppTemplate orgAppTemplat = MsgAppUtils.getOrgAppTemplat(JsonUtils.toJsonString(appMessageVo));
                //获取推送图文表信息
                ImageTemplate tmpTemplate = new ImageTemplate();
                tmpTemplate.setTemplateCode(orgAppTemplat.getLibraryTemplateCode());
                tmpTemplate.setPlatformType(orgAppTemplat.getPlatformType());
                List<ImageTemplate> tmpTemplates = imageTemplateDao.select(tmpTemplate);
                if(tmpTemplates.size() < 1){
                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取ImageTemplate失败：" + JsonUtils.toJsonString(tmpTemplate));
                    responseObject.setResultCodeAndMessage("8202" , "获取ImageTemplate失败：" + JsonUtils.toJsonString(tmpTemplate));
                    return;
                }

                tmpTemplate = tmpTemplates.get(0);

                //获取推送图文详情信息
                ImageTemplateList imageTemplateList = new ImageTemplateList();
                imageTemplateList.setImageTemplateId(tmpTemplate.getId());
                imageTemplateList.setImageTemplateCode(tmpTemplate.getTemplateCode());
                List<ImageTemplateList> templateLists = imageTemplateListDao.select(imageTemplateList);
                if(templateLists.size() < 1){
                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取ImageTemplateList失败：" + JsonUtils.toJsonString(templateLists));
                    responseObject.setResultCodeAndMessage("8202" , "获取ImageTemplateList失败：" + JsonUtils.toJsonString(templateLists));
                    return;
                }
                imageTemplateList = templateLists.get(0);

                //获取支付配置
                PaymentSettingResponse paymentSettingResponse = MsgAppUtils.getPaymentSettingResponse(appMessageVo.getPlatformOrgAppCode() ,
                        StringUtils.isBlank(appMessageVo.getDevOrgCode())? "" : appMessageVo.getDevOrgCode() , orgAppTemplat.getPlatformType().intValue());

                if(paymentSettingResponse == null){
                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取PaymentSettingResponse支付配置失败：" + JsonUtils.toJsonString(appMessageVo));
                    responseObject.setResultCodeAndMessage("8202" , "MsgImgAppPushRunnable 获取PaymentSettingResponse支付配置失败：" + JsonUtils.toJsonString(appMessageVo));
                    return;
                }

                JSONObject param = new JSONObject();
                Response response = null;
                //根据推送平台不同分发
                if(orgAppTemplat.getPlatformType() == 1) {  //微信
                    WechatMessageNewsImgVo newsImgVo = new WechatMessageNewsImgVo();
                    newsImgVo.setAppId(paymentSettingResponse.getPayAppId());
                    newsImgVo.setAppSecret(paymentSettingResponse.getSecretKey());
                    newsImgVo.setPicurl(imageTemplateList.getImageUrl());
                    newsImgVo.setUrl(imageTemplateList.getActionUrl());
                    newsImgVo.setTitle(imageTemplateList.getImageTitle());
                    newsImgVo.setDescription(imageTemplateList.getImageContent());
                    newsImgVo.setTouser(appMessageVo.getOpenId());

                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Wechat图文消息发送："+ JsonUtils.toJsonString(newsImgVo));
                    response = WechatPayService.callHumpFromInternal("yyt.wechatpay.wechat.message.imgtext.send", JsonUtils.toJsonString(newsImgVo));
                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Wechat图文消息返回："+ JsonUtils.toJsonString(response));
                    responseObject.setResultCodeAndMessage(response.getResultCode() , "MsgImgAppPushRunnable 调用Wechat图文消息返回：" + response.getResultMessage());
                }else if(orgAppTemplat.getPlatformType() == 2){ //支付宝
                    param.put("payment_setting" , paymentSettingResponse);
                    param.put("to_user" , appMessageVo.getOpenId());
                    param.put("image_url" , imageTemplateList.getImageUrl());
                    param.put("action_name" , imageTemplateList.getActionName());
                    param.put("desc" , imageTemplateList.getImageContent());
                    param.put("title" , imageTemplateList.getImageTitle());
                    param.put("url" , imageTemplateList.getActionUrl());

                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Alipay图文消息发送："+ JsonUtils.toJsonString(param));
                    response = AlipayService.callHumpFromInternal("yyt.alipay.alipaymessage.image.send", JsonUtils.toJsonString(param));
                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Alipay图文消息发送返回："+ JsonUtils.toJsonString(response));
                    responseObject.setResultCodeAndMessage(response.getResultCode() , "MsgTmpAppPushRunnable 调用Alipay模板消息返回：" + response.getResultMessage());
                }else{
                    Log.i(LogScene.MSG_IMG,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取OrgAppTemplate 发送平台错误，请检查数据库配置：" + orgAppTemplat.getPlatformType());
                    responseObject.setResultCodeAndMessage("8202" , "MsgImgAppPushRunnable 获取OrgAppTemplate 发送平台错误，请检查数据库配置：" + orgAppTemplat.getPlatformType());
                    return;
                }
            }
        } catch (Exception e) {
            Log.e(LogScene.MSG_IMG,"MsgImgAppPushRunnable 执行方法异常！" ,e);
            responseObject.setResultCodeAndMessage(Response.FAILURE_CODE , "MsgImgAppPushRunnable 执行方法异常！");
        }
    }

}
